package gr.atc.epart;

import gr.atc.epart.actions.Action.Type;
import gr.atc.epart.net.ActionsPage;
import gr.atc.epart.net.ActionsPage.SortBy;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class SearchActivity extends Activity {
	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID_TO = 1;
	static final int DATE_DIALOG_ID_FROM = 2;

	int YearTo = 2010, monthTo=0, dayTo=1, YearFrom=2010, monthFrom=0, dayFrom=1;

	EditText fromText = null;
	EditText toText = null;
	String text, creator;

	String[] tags;
	Spinner sortBySpinner;
	Date startDate, stopDate;
	SortBy sortBy;
	Type actionType;
	String typeString;
	ProgressDialog progressDialog;
	EditText creatorTxt;
	EditText tagsTxtEdit;
	EditText searchText;
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        progressDialog = new ProgressDialog(this);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.searchform);
       
        Calendar current = Calendar.getInstance();
        dayFrom = current.get(Calendar.DAY_OF_MONTH);
        dayTo = current.get(Calendar.DAY_OF_MONTH);
        
        monthFrom = current.get(Calendar.MONTH);
        monthTo = current.get(Calendar.MONTH);
        
        YearFrom = current.get(Calendar.YEAR);
        YearTo = current.get(Calendar.YEAR);
        
        searchText = (EditText) findViewById(R.id.Text_Edit);
		 tagsTxtEdit = (EditText) findViewById(R.id.Tags_Edit);
        creatorTxt = (EditText) findViewById(R.id.Creator_Edit);
        
    	Button fromButton = (Button) findViewById(R.id.frombutton);
    	fromButton.setOnClickListener(fromBtnListener);
    	
    	Button toButton = (Button) findViewById(R.id.tobutton);
    	toButton.setOnClickListener(fromBtnListener);
    	
    	Button searchButton = (Button) findViewById(R.id.searchbutton);
    	searchButton.setOnClickListener(buttonListener);
    	
    	Button clearButton = (Button) findViewById(R.id.clearbutton);
    	clearButton.setOnClickListener(buttonListener);
    	
    	
    	fromText = (EditText) findViewById(R.id.fromtext);
    	toText = (EditText) findViewById(R.id.totext);
    	
        sortBySpinner = (Spinner) findViewById(R.id.sortbyspinner);
        Spinner typeSpinner = (Spinner) findViewById(R.id.typespinner);
        
        ArrayAdapter<String> sortByAttributes = 
        	new ArrayAdapter<String>(this, R.layout.sortbyspinnerview,
        	getResources().getStringArray(R.array.sortBy));
      
        sortBySpinner.setAdapter(sortByAttributes);
        
                
            ArrayAdapter<String> typeAdapter = 
            	new ArrayAdapter<String>(this, R.layout.sortbyspinnerview,
            	getResources().getStringArray(R.array.type));
        
            typeSpinner.setAdapter(typeAdapter);
            
            typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        	        Object item = parent.getItemAtPosition(pos);
        	        typeString = item.toString();        	    	
        	    }
        	    public void onNothingSelected(AdapterView<?> parent) {
        	    }
        	});
    	
        
    }
	
	

	private OnClickListener buttonListener = new OnClickListener() {
		public void onClick(View v) {
			
			if (v == findViewById(R.id.clearbutton)) {
				
				fromText.setText(""); 
				toText.setText("");
				creatorTxt.setText("");
				tagsTxtEdit.setText("");
				searchText.setText("");
				
			} else if (v == findViewById(R.id.searchbutton)) {

				EPartClient client = new EPartClient();

				SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
				Date startDate = null;
				Date endDate = null;
			
				String fromString = fromText.getText().toString();
				String toString = toText.getText().toString();
				
				try {
					if (fromString != null && !fromString.equals("")) {
						startDate = formatter.parse(fromString);
					}  
				} catch (ParseException e) {
		
					e.printStackTrace();
				}

				try {
					if (toString != null && !toString.equals("")) {
						endDate = formatter.parse(toString);
					}  
					
				} catch (ParseException e) {
		
					e.printStackTrace();
				}
				
		
				String tagsTxt = tagsTxtEdit.getText().toString();
			   
			    String [] tags = tagsTxt.split(" ");
			    if (tags.length == 0 ) {
			    	tags = null;
			    }
		
				String creator = creatorTxt.getText().toString();
				
				if (creator.equals("") || creator.equals(" ")) {
					creator = "all";
				}
			
				String searchtext = searchText.getText().toString();
				
				progressDialog.setMessage("Please wait...");
				progressDialog.setIndeterminate(true);
				progressDialog.setCancelable(false);
				progressDialog.show();
			
				
				Type type = Enum.valueOf(Type.class, typeString);
				ActionsPage actions = client.getActions(type, searchtext,creator, startDate, endDate, tags, SortBy.Popularity,1,100);
				EPartVolatileDataStore.getInstance().setActionsList(
						actions.getActions());

				progressDialog.dismiss();
				
				Intent actionsListIntent = new Intent();
				actionsListIntent.setClassName("gr.atc.epart",
						"gr.atc.epart.ActionsViewActivity");
				startActivity(actionsListIntent);
			
			}

		}

	};

	private OnClickListener fromBtnListener = new OnClickListener() {
		public void onClick(View v) {
			if (v == findViewById(R.id.frombutton)) {
				showDialog(DATE_DIALOG_ID_FROM);
			} else if (v == findViewById(R.id.tobutton)) {
				showDialog(DATE_DIALOG_ID_TO);
			} else if (v == findViewById(R.id.fromtext)) {
				showDialog(DATE_DIALOG_ID_FROM);
			}
		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID_TO:
			return new DatePickerDialog(this, mDateSetListener, YearTo,
					monthTo, dayTo);
		case DATE_DIALOG_ID_FROM:
			return new DatePickerDialog(this, mDateSetListenerFrom, YearFrom,
					monthFrom, dayFrom);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			YearTo = year;
			monthTo = monthOfYear;
			dayTo = dayOfMonth;

			toText.setText(dayTo + "-" + (monthTo + 1) + "-" + YearTo);
			/*Toast.makeText(
					getBaseContext(),
					"You have selected : " + dayTo + "-" + (monthTo + 1) + "-"
							+ YearTo, Toast.LENGTH_SHORT).show();*/
		}

	};

	private DatePickerDialog.OnDateSetListener mDateSetListenerFrom = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			YearFrom = year;
			monthFrom = monthOfYear;
			dayFrom = dayOfMonth;

			fromText.setText(dayFrom + "-" + (monthFrom + 1) + "-" + YearFrom);
			/*Toast.makeText(
					getBaseContext(),
					"You have selected : " + dayFrom + "-" + (monthFrom + 1)
							+ "-" + YearFrom, Toast.LENGTH_SHORT).show();*/

		}

	};
	
	public void createAlert() {
	    
	      AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
	        dlgAlert.setMessage("Wrong date format: Please set the date as day/month/year");
	        dlgAlert.setTitle("Error");
	        dlgAlert.setPositiveButton("OK", null);
	        dlgAlert.setCancelable(true);
	        dlgAlert.create();
	        dlgAlert.show();
	}
	
}
